<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\Medium\Action\Dashboard;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Medium\Action\Dashboard\Traits\MediumTrait;
use MoChat\App\Medium\Action\Dashboard\Traits\RequestTrait;
use MoChat\App\Medium\Contract\MediumContract;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 添加 - 动作.
 * @Controller
 */
class Store extends AbstractAction
{
    use ValidateSceneTrait;
    use RequestTrait;
    use MediumTrait;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/medium/store", methods="POST")
     */
    public function handle(): array
    {
        // 请求参数
        $params = $this->request->inputs(
            ['type', 'isSync', 'content', 'mediumGroupId', 'isBatch'],
            ['isSync' => 2, 'mediumGroupId' => 0, 'isBatch' => 0, 'size' => 0]
        );

        // 验证
//        $this->validated($params);
        // 数据整理
        $userInfo = user();
        $insertId = 0;
        // 数据操作
        Db::beginTransaction();
        try {
            // 批量添加图片
            if ((int) $params['type'] === 2 && (int) $params['isBatch'] === 1) {
                $data = [];
                foreach ($params['content'] as $item) {
                    $item['size'] = empty($params['size'])?$this->size($item):$params['size'];
                    $data[] = [
                        'type' => $params['type'],
                        'is_sync' => $params['isSync'],
                        'corp_id' => $userInfo['corpIds'][0],
                        'medium_group_id' => $params['mediumGroupId'],
                        'user_id' => $userInfo['id'],
                        'user_name' => $userInfo['name'],
                        'content' => Json::encode($item),
                    ];
                }
                // 入库
                $this->container->get(MediumContract::class)->createMedia($data);
            } else {
                $params['content']['size'] = empty($params['size'])?$this->size($params['content']):$params['size'];
                $params = array_merge($params, [
                    'corp_id' => $userInfo['corpIds'][0],
                    'user_id' => $userInfo['id'],
                    'user_name' => $userInfo['name'],
                    'content' => Json::encode($params['content']),
                ]);
                // 入库
                $insertId = $this->container->get(MediumContract::class)->createMedium($params);
                if (! $insertId) {
                    throw new CommonException(ErrorCode::SERVER_ERROR, '素材添加失败');
                }
            }
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '引流链接创建失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, $e->getMessage()); // '活动创建失败'
        }

        return ['id' => $insertId];
    }
}
